<template>
  <div>
    <p class="text-info"><i class="el-icon-info"></i> 每个用户可以拥有多个角色，并继承角色的权限</p>
    <br/>
    <div v-loading="loading">
      <el-transfer
      filterable
        v-model="roles"
        :data="roleList"
        :props="transfer.props"
        :titles="transfer.titles"
        :buttonTexts="transfer.buttonText"
      >
        <span slot-scope="{ option }">{{ option.display_name }}<span class="red">【{{option.name}}】</span></span>

      </el-transfer>
      <br/>
      <div class="text-center">
        <el-button :loading="btnLoad" @click="allotRoles">更新</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { roleList, userInfo,userRole } from "@/api";
export default {
  data() {
    return {
      loading: true,
      roleList: [],
      roles: [2],
      btnLoad:false,
      transfer: {
        titles: ["未选择", "已选择"],
        buttonText: ["移除", "添加"],

        props: {
          key: "id",
          label: "display_name"
        }
      }
    };
  },
  props: ["pdata"],
  created() {
    roleList(
      {},
      res => {
        this.loading = false;
        this.roleList = res.data;
        this.fetchInfo()
      },
      err => {
        this.loading = false;
      }
    );
  },
  methods: {
    fetchInfo() {
      userInfo(
        this.pdata.id,
        res => {
          this.loading = false;
          let data = res.data;
          if (data) {
            let roles = [];
            for (let i in data.roles) {
              roles.push(data.roles[i].id);
            }
            this.roles = roles;
          }
        },
        err => {
          this.loading = false;
        }
      );
    },
    allotRoles(){
      this.btnLoad = true
      userRole(this.pdata.id,this.roles,res=>{
        this.btnLoad=false
        this.$emit('close',true)
      },err=>{
        this.btnLoad = false
      })
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
